<?php

namespace app\admin\model;

use app\lib\Qiniu;

class Harm extends Base
{

    // 数据表主键 复合主键使用数组定义 不设置则自动获取
    protected $pk = 'id';

    // 字段验证规则
    protected $validate = false;


    public static function _after_insert($data){
        //多图
        if(isset($data['imgIds']) && !empty($data['imgIds'])){
            foreach ((array)$data['imgIds'] as $key => $item) {
                Image::where('id', $item)->update(['relatedId' => $data['id'], 'controller' => 'Harm', 'relatedTable' => 'harm', 'tag' => 'imglist', 'sorting' => $key]);
            }
        }
    }

    public static function _after_update($data){
        //多图
        if(isset($data['imgIds']) && !empty($data['imgIds'])){
            foreach ((array)$data['imgIds'] as $key => $item) {
                Image::where('id', $item)->update(['relatedId' => $data['id'], 'controller' => 'Harm', 'relatedTable' => 'harm', 'tag' => 'imglist', 'sorting' => $key]);
            }
        }
    }


    public static function _after_delete($id){  //删除图片记录及空间中的图片
        if(is_array($id)){
            $list = Image::where('relatedTable', 'harm')->whereIn('relatedId', $id)->select();
        }else{
            $list = Image::where('relatedTable', 'harm')->where('relatedId', $id)->select();
        }

        $Qiniu = new Qiniu();
        foreach ((array)$list as $v) {
            $key = substr(strrchr($v['imgUrl'], '/'), 1);
            $res = $Qiniu->delImg($key);  //删除图片
            Image::where('id',$v['id'])->delete();
        }
    }
}